package com.example.demo.chat.myhandler;

import com.alibaba.fastjson.JSON;
import com.example.demo.chat.MessageType;
import com.example.demo.chat.NettyAsyncServer;
import com.example.demo.chat.Result;
import com.example.demo.chat.message.ChatMsg;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

public class ChatHandler {
    public static void execute(TextWebSocketFrame frame, ChannelHandlerContext ctx){
        try {
            ChatMsg chat= JSON.parseObject(frame.text(),ChatMsg.class);
            System.out.println(chat);
            switch (MessageType.match(chat.getType())){
                case PRIVATE:
                    if(StringUtil.isNullOrEmpty(chat.getTarget())){
                        ctx.channel().writeAndFlush(Result.fail("发送失败，发送消息前指定接收对象"));
                        return;
                    }
                    Channel channel=NettyAsyncServer.player.get(chat.getTarget());
                    Channel channel1=NettyAsyncServer.player.get(chat.getName());
                    if (null==channel || !channel.isActive()){
                        System.out.println("不在线");
                        ctx.channel().writeAndFlush(Result.fail("消息失败"+chat.getTarget()+"不在线"));
                    }else {
                        System.out.println("私发");
                        channel.writeAndFlush(Result.sucess("私聊消息("+chat.getName()+")", chat.getContent()));
                        channel1.writeAndFlush(Result.sucess("私聊消息("+"我)", chat.getContent()));
                } break;
                default:
                    System.out.println("不支持");
                    ctx.channel().writeAndFlush(Result.fail("不支持消息类型"));
                break;
                case GROUP: NettyAsyncServer.GROUP.writeAndFlush(Result.sucess("世界消息"+chat.getName(),chat.getContent()));
            }
        }catch (Exception e){
            ctx.channel().writeAndFlush(Result.fail("格式错误"));
        }

    }
}
